<script setup>
import { addNPApi, deleteAllNPApi, getNPByIdApi, getNPPageApi, updateNPApi } from '@/api/nursingProject';
import { onMounted, ref } from 'vue';
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';


//声明token
const token = ref('')
const ids = ref([])
const form = ref({
    name: '',
    orderNo: '',
    unit: '',
    price: '',
    image: '',
    nursingRequirement: '',
    status: 1,
    remark: '',
})
const nursingProjectRef = ref(null)
const title = ref('')
const open = ref(false)
const NPList = ref([])
const page = ref(1)
const pageSize = ref(10)
const totalSize = ref(0)
const searchForm = ref({
    name: '',
})




const handleDelete = async (row) => {
    ids.value = row.id
    handleDeletes()
}
const handleDeletes = async () => {
    const result = await deleteAllNPApi(ids.value)
    if (result.code === 1) {
        ElMessage.success('删除成功')
        getPage()
    } else {
        ElMessage.error('删除失败')
    }
}
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
}
const handleUpdate = async (row) => {
    title.value = '修改护理项目'
    open.value = true
    const result = await getNPByIdApi(row.id)
    form.value = result.data
}
const cancel = () => {
    open.value = false
    reset()
}
const submitForm = async () => {
    if (!nursingProjectRef) return
    await nursingProjectRef.value.validate(async (valid, fields) => {
        if (valid) {
            let result = null;
            if (form.value.id) {
                result = await updateNPApi(form.value)
            } else {
                result = await addNPApi(form.value)
            }
            if (result.code === 1) {
                ElMessage.success('操作成功')
                open.value = false
                reset()
                getPage()
            } else {
                ElMessage.error('操作失败')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const rules = ref({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ]
})
// 头像上传成功后
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
    form.value.image = response.data
}


// 头像上传之前
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像必须是jpg或者png格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 3) {
        ElMessage.error('头像不能超过3MB')
        return false
    }
    return true
}
const handleAdd = () => {
    title.value = '添加护理项目'
    reset()
    open.value = true
}
const reset = () => {
    form.value.name = ''
    form.value.orderNo = ''
    form.value.unit = ''
    form.value.price = ''
    form.value.image = ''
    form.value.nursingRequirement = ''
    form.value.status = 1
    form.value.remark = ''
    if (nursingProjectRef.value) {
        nursingProjectRef.value.resetFields()
    }
}
const resetSearchForm = () => {
    page.value = 1
    pageSize.value = 10
    searchForm.value = {
        name: '',
    }
    getPage()
}
const getPage = async () => {
    const result = await getNPPageApi(page.value, pageSize.value, searchForm.value.name)
    NPList.value = result.data.rows
    totalSize.value = result.data.total
}


const handleSizeChange = (val) => {
    pageSize.value = val
    page.value = 1
    getPage()
}
const handleCurrentChange = (val) => {
    page.value = val
    getPage()
}


onMounted(() => {
    getPage()
    //加载localStorage存储的员工登录信息
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
        token.value = JSON.parse(userInfo).token
    }
})
</script>


<template>


    <!-- 添加或修改护理项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="nursingProjectRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="排序号" prop="orderNo">
                <el-input v-model="form.orderNo" placeholder="请输入排序号" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
                <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
                <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
            <el-form-item label="图片" prop="image">
                <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'token': token }"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="form.image" :src="form.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="护理要求" prop="nursingRequirement">
                <el-input v-model="form.nursingRequirement" placeholder="请输入护理要求" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>


    <el-form :inline="true" :model="searchForm">
        <el-form-item label="项目名称">
            <el-input v-model="searchForm.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getPage">查询</el-button>
            <el-button @click="resetSearchForm">重置</el-button>
        </el-form-item>
    </el-form>
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-button type="danger" :disabled="multiple" @click="handleDeletes">删除</el-button>


    <el-table :data="NPList" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" />
        <el-table-column type="index" label="序号" width="100px" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="orderNo" label="排序号" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="price" label="价格" />
        <el-table-column label="图片">
            <template #default="scope">
                <img :src="scope.row.image" style="width: 100px; height: 100px;" />
            </template>
        </el-table-column>
        <el-table-column prop="nursingRequirement" label="护理要求" />
        <el-table-column prop="status" label="状态">
            <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
                <el-tag v-else type="danger">禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="200px">
            <template #default="scope">
                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
        :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>


<style scoped>
/* 头像上传样式 */
.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}


.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}


.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>